﻿//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------

using UnityEngine;
using UnityGameFramework.Runtime;

namespace Adventure
{
    /// <summary>
    /// 可作为目标的实体类。
    /// </summary>
    public abstract class FigureObject : Entity
    {
        [SerializeField]
        private FigureData m_FigureData = null;

        public bool IsDead
        {
            get
            {
                return m_FigureData.CurrentHP <= 0;
            }
        }

        /// <summary>
        /// 施加伤害
        /// </summary>
        /// <param name="attacker"></param>
        /// <param name="damageHP"></param>
        public virtual void ApplyDamage(Entity attacker, int damageHP)
        {
            float fromHPRatio = m_FigureData.HPRatio;
            m_FigureData.CurrentHP -= damageHP;
            float toHPRatio = m_FigureData.HPRatio;
            if (fromHPRatio > toHPRatio)
            {
                GameEntry.HPBarlComponent.ShowHPBar(new HpBarItemData()
                {
                    owner = attacker,                  
                    fromHPRatio = fromHPRatio,
                    toHPRatio = toHPRatio,
                });
                GameEntry.Sound.PlaySound(10003);
            }

            if (m_FigureData.CurrentHP <= 0)
            {               
                OnDead(attacker);
            }

            if (attacker.transform.tag == "Player")
            {
                GameEntry.ArchiveData.Data.player.CurrentHP = m_FigureData.CurrentHP;

                if (GameEntry.ArchiveData.Data.player.CurrentHP <=0)
                {
                    GameEntry.ArchiveData.Data.player.CurrentHP = 1;
                }

            }
           
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnInit(object userData)
#else
        protected internal override void OnInit(object userData)
#endif
        {
            base.OnInit(userData);
        
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnShow(object userData)
#else
        protected internal override void OnShow(object userData)
#endif
        {
            base.OnShow(userData);

            m_FigureData = userData as FigureData;
            if (m_FigureData == null)
            {
                Log.Error("Targetable object data is invalid.");
                return;
            }
        }

        protected virtual void OnDead(Entity attacker)
        {
            GameEntry.Entity.HideEntity(this);
        }

       
    }
}
